package net.gdface.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import net.gdface.annotations.ActiveOnClass;
/**
 * @author guyadong
 * @since 2.7.0
 */
@ActiveOnClass(JSON.class)
public class FastJsonSupport extends JsonSupport{
	private final SerializerFeature[] features = new SerializerFeature[]{SerializerFeature.WriteMapNullValue,SerializerFeature.WriteDateUseDateFormat,SerializerFeature.WriteNonStringKeyAsString};
	private final SerializerFeature[] indent = new SerializerFeature[]{SerializerFeature.WriteMapNullValue,SerializerFeature.WriteDateUseDateFormat,SerializerFeature.WriteNonStringKeyAsString,SerializerFeature.PrettyFormat};
	@Override
	public String toJSONString(Object object, boolean prettyFormat) throws JsonSupportException{
		try {
			return JSON.toJSONString(object, prettyFormat ? indent : features);
		} catch (JSONException e) {
			throw new JsonSupportException(e);
		}
	}
	@Override
	public Object parseOrEmptyMap(String json) throws JsonSupportException{
		try {
			if(null == json || 0 == json.length()){
				return new JSONObject(true);
			}
			return JSON.parseObject(json,JSON.class);
		} catch (JSONException e) {
			throw new JsonSupportException(e);
		}
	}
	@Override
	public <T>T doParse(String json,Class<T> targetType) throws JsonSupportException{
		try {
			return JSON.parseObject(json,targetType);
		} catch (Exception e) {
			throw new JsonSupportException(e);
		}
	}
}
